package com.dtx.exercise.array;

import com.dtx.exercise.apiinterface.LineStruct;

public class Array<T> implements LineStruct<T> {

    private Object[] array;
    private int size;
    private int length = 4;

    @Override
    public T add(T element) {
        this.capacity();
        array[size] = element;
        size++;
        return element;
    }

    @Override
    public T insert(int index, T element) throws Exception {
        if(index < 0 || index > size){
            throw new Exception("超出数组实际范围");
        }
        this.capacity();
        for (int i = size;i>=index-1;i--){
            array[i+1] = array[i];
        }
        array[index - 1] = element;
        size++;
        return element;
    }

    @Override
    public T delete(int index) throws Exception {
        if (isEmpty()) {
            throw new IndexOutOfBoundsException("数组没有元素，无法删除");
        }
        if(index < 0 || index > size){
            throw new Exception("超出数组实际范围");
        }
        T deletedElement = (T) array[index-1];
        for (int i = index-1;i<size;i++){
            array[i] = array[i+1];
        }
        size--;
        return deletedElement;
    }

    @Override
    public int size() {
        return this.size;
    }

    @Override
    public void output() throws Exception {
        if (isEmpty()) {
            throw new Exception("数组元素为空");
        }
        for (int i = 0; i < size; i++) {
            System.out.println(array[i]);
        }
    }

    @Override
    public T query(T element) {
        T temp = null;
        int index = 0;
        for (int i = 0; i < size; i++) {
            if (array[i].equals(element)) {
                temp = element;
                index = i+1;
            }
        }
        if (index!=0) {
            System.out.println(temp+"元素在第"+index+"位置");
        }else {
            System.out.println(element+"不在该数组里");
        }
        return temp;
    }

    /**
     * 数组初始化或者以1.5倍容量对数组扩容
     */
    private void capacity(){
        //数组初始化
        if (array==null) {
            this.array = new Object[this.length];
        }
        //以1.5倍对数组扩容
        if (this.size - (this.length - 1) >=0) {
            this.length = this.length+(this.length>>1);
            Object[] arrayNew = new Object[this.length];
            System.arraycopy(array,0,arrayNew,0,array.length);
            array = arrayNew;
        }
    }

    public boolean isEmpty(){
        return this.size==0;
    }
}
